package com.yangjie.common.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;

public abstract class JPADao<T extends Object> implements Dao<T> {
	@Inject
	private EntityManagerFactory  entityManagerFactory = null;
	
	protected EntityManager entityManager = null;
	protected Class<T> domainClass = null;

	protected Class<T> getDomainClass() {
		if (domainClass == null) {
			ParameterizedType thisType = (ParameterizedType) (getClass().getGenericSuperclass());
			this.domainClass = (Class<T>) thisType.getActualTypeArguments()[0];
		}
		return domainClass;
	}

	
	@PersistenceUnit
	public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;
		entityManager = entityManagerFactory.createEntityManager();
	}


	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}


	public void create(T t) {
		entityManager.persist(t);
	}

	@Override
	public T get(Serializable id) {
		// TODO Auto-generated method stub
		return entityManager.find(getDomainClass(), id);
	}

//	@Override
//	public T load(Serializable id) {
////		return entityManager.find(entityClass, primaryKey);
//	}

	@Override
	public List<T> getAll() {
		return entityManager.createQuery("SELECT T FROM " + getDomainClass().getName() + " T ").getResultList();
	}

	@Override
	public void update(T t) {
		entityManager.merge(t);

	}

	@Override
	public void delete(T t) {
		entityManager.remove(t);

	}

	@Override
	public void deleteById(Serializable id) {
		// TODO Auto-generated method stub

	}

	@Override
	public void deleteAll() {
		// TODO Auto-generated method stub

	}

	@Override
	public long count() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public boolean exists(Serializable id) {
		// TODO Auto-generated method stub
		return false;
	}

}
